<?php

namespace app\modules\api\controllers;

use app\models\AgentLoginForm;
use app\models\ApiException;
use app\models\User;
use app\models\UserLoginForm;
use app\models\Util;
use Yii;
use yii\base\Exception;

/**
 * 用户处理
 * Class UserController
 * @package app\modules\api\controllers
 */
class UserController extends BaseController
{
    /**
     * 用户登录
     * 输入
     * {
     *     username,
     *     password
     * }
     * 输出
     * {
     *     token
     * }
     * @throws ApiException
     */
    public function actionLogin()
    {
        $this->checkJson([
            [['username', 'password'], 'required', 'message' => '缺少必要参数。'],
        ]);

        $type = $this->json('type', 'user');
        if ($type == 'agent') {
            $model = new AgentLoginForm();
            $model->setAttributes($this->json);
            if (!$model->login()) {
                throw new ApiException('USER_LOGIN', '登录失败，请检查登录参数。', $model->errors);
            }
            $agent = $model->getAgent();
            $token = $agent->generateToken($this->app_id);
        } elseif ($type == 'user') {
            $model = new UserLoginForm();
            $model->setAttributes($this->json);
            if (!$model->login()) {
                throw new ApiException('USER_LOGIN', '登录失败，请检查登录参数。', $model->errors);
            }
            $user = $model->getUser();
            $token = $user->generateToken($this->app_id);
        } else {
            throw new ApiException('PARAM', '登录类型错误。');
        }

        return [
            'token' => $token,
        ];
    }

    /**
     * 重新获取Token
     * 输入
     * {}
     * 输出
     * {
     *     token
     * }
     * @throws ApiException
     */
    public function actionNewToken()
    {
        if (!Yii::$app->user->isGuest) {
            $user = User::findOne(['id' => Yii::$app->user->id]);
            return [
                'token' => $user->generateToken($this->app_id),
            ];
        }
        $token = Yii::$app->request->headers->get('token');
        if (empty($token)) {
            $token = $this->get('token');
        }
        if (empty($token)) {
            throw new ApiException('TOKEN', '没有找到Token参数。');
        }
        try {
            $payloadJson = Util::checkJWT($token);
            $user = User::findOne(['id' => $payloadJson['uid']]);
            return [
                'token' => $user->generateToken($this->app_id),
            ];
        } catch (Exception $e) {
            throw new ApiException('TOKEN', $e->getMessage());
        }
    }
}
